#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int tickets = 10000;  //假设有一万张票

void *callfunc(void *args)
{
    pthread_mutex_t *mutex_p = static_cast<pthread_mutex_t*>(args);
    while (true)
    {
        pthread_mutex_lock(mutex_p);  //加锁
        if(tickets > 0)
        {
            usleep(1000);
            cout << "抢到票了，tickets = " << tickets << endl;
            tickets--;
            pthread_mutex_unlock(mutex_p);  //解锁
        }
        else
        {
            cout << "没有票了...." << endl;
            pthread_mutex_unlock(mutex_p);  //这里不解锁，无票时会导致线程卡死在这里，即死锁
            break;
        }
        //sleep(1);
    }
    return nullptr;
}

int main()
{
	pthread_t tid;
	static pthread_mutex_t mutex =  PTHREAD_MUTEX_INITIALIZER; 
	pthread_create(&tid, nullptr, callfunc, (void*)&mutex);
	pthread_join(tid, nullptr);
    return 0;
}
